let http = {};

/**
 * 基于 fetch 封装的 GET请求
 * @param url
 * @param params {}
 * @param headers
 * @returns {Promise}
 */
http.get = function (url, params, headers = {"Content-Type": "application/json;charset=UTF-8"}) {
    // let headers = new Headers();
    // headers.append( "Content-Type", "application/json");
    if (params) {
        let paramsArray = [];
        //encodeURIComponent
        Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]));
        if (url.search(/\?/) === -1) {
            url += '?' + paramsArray.join('&')
        } else {
            url += '&' + paramsArray.join('&')
        }
    }
    return new Promise(function (resolve, reject) {
        fetch(url, {
            method: 'GET',
            headers: headers,
        })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                } else {
                    reject({status: response.status})
                }
            })
            .then((response) => {
                resolve(response);
            })
            .catch((err) => {
                reject({status: -1, error: err});
            })
    })
};


/**
 * 基于 fetch 封装的 POST请求  FormData 表单数据
 * @param url
 * @param formData
 * @param headers
 * @returns {Promise}
 */
http.post = function (url, formData, headers = {"Content-Type": "application/json;charset=UTF-8"}) {
    return new Promise(function (resolve, reject) {
        fetch(url, {
            method: 'POST',
            headers: headers,
            body: formData,
        })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                } else {
                    reject({status: response.status})
                }
            })
            .then((response) => {
                resolve(response);
            })
            .catch((err) => {
                reject({status: -1, error: err});
            })
    })
};

/**
 * fetch设置timeout
 * https://blog.csdn.net/u010688637/article/details/56005394
 * @param fetch_promise
 * @param timeout
 * @returns {Promise<unknown>}
 */
http.fetchWithTimeout = function (fetch_promise, timeout = 1000 * 10) {
    let abort_fn = null;

    //这是一个可以被reject的promise
    let abort_promise = new Promise(function (resolve, reject) {
        abort_fn = function () {
            reject('promise timeout');
        };
    });

    //这里使用Promise.race，以最快 resolve 或 reject 的结果来传入后续绑定的回调
    let abortable_promise = Promise.race([
        fetch_promise,
        abort_promise
    ]);

    setTimeout(function () {
        abort_fn();
    }, timeout);

    return abortable_promise;
};

export default http;
